package com.pm.buglist.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pm.buglist.domain.Bugs;
import com.pm.buglist.mapper.BugAnalysisMapper;
import com.pm.buglist.mapper.BugsMapper;
import com.pm.buglist.service.BugAnalysisService;
import com.pm.common.config.ParamConfig;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.core.domain.entity.SysRole;
import com.pm.common.core.domain.entity.SysUser;
import com.pm.common.core.domain.model.LoginUser;
import com.pm.common.enums.BugsStatus;
import com.pm.common.enums.RoleKey;
import com.pm.common.utils.SecurityUtils;
import com.pm.common.utils.WeChatNoteUtils;
import com.pm.system.mapper.SysUserMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import com.pm.buglist.domain.BugAnalysis;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * bugs分析对策表 服务实现类
 * </p>
 *
 * @author wwm
 * @since 2023-12-14
 */
@Service
public class BugAnalysisServiceImpl extends ServiceImpl<BugAnalysisMapper, BugAnalysis> implements BugAnalysisService {

    @Resource
    private WeChatNoteUtils weChatNoteUtils;

    @Resource
    private BugsMapper bugsMapper;

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private ParamConfig paramConfig;

    @Override
    public AjaxResult insertAnalysis(BugAnalysis analysis) {
        //获取当前登录用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<SysRole> roles = loginUser.getUser().getRoles();
        Boolean flag=false;
        if(!CollectionUtils.isEmpty(roles)){//验证当前人员是否是品质人员
            for (SysRole role : roles) {
                String roleKey = role.getRoleKey();
                if(roleKey.equals(RoleKey.RD.getCode())){
                    flag=true;
                    break;
                }
            }
        }
        if(!flag){
            return AjaxResult.error("你无权限执行此操作");
        }
        analysis.setCreateTime(LocalDateTime.now());
        analysis.setCreateUser(loginUser.getUserId());
        analysis.setHandleUser(loginUser.getUserId());
        baseMapper.insert(analysis);
        return AjaxResult.success("添加成功");
    }

    @Override
    public AjaxResult updateAnalysis(BugAnalysis analysis) {
        //获取当前登录用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<SysRole> roles = loginUser.getUser().getRoles();
        Boolean flag=false;
        if(!CollectionUtils.isEmpty(roles)){//验证当前人员是否是研发人员
            for (SysRole role : roles) {
                String roleKey = role.getRoleKey();
                if(roleKey.equals(RoleKey.RD.getCode()) || roleKey.equals(RoleKey.WBGYS.getCode())){
                    flag=true;
                    break;
                }
            }
        }
        if(!flag){
            return AjaxResult.error("你无权限执行此操作");
        }
        //获取需要修改的分析id
        Integer id = analysis.getId();
        //获取bugid
        Long bugId = analysis.getBugId();
        if(ObjectUtils.isEmpty(id)){
            return AjaxResult.error("后台找不到要修改的数据");
        }
        //查询bug分析数据
        BugAnalysis bugAnalysis = baseMapper.selectById(id);
        //验证当前的用户是否是bug分析的处理人/创建人
        if(!bugAnalysis.getHandleUser().equals(loginUser.getUserId())){
            return AjaxResult.error("你不是当前bug对策的处理人，无权修改当前的分析对策！");
        }
        //根据bugId查询最新的bug分析
        BugAnalysis newAnalysis = baseMapper.selectBugAnalysisByBid(bugId);
        if(!id.equals(newAnalysis.getId())){//判断当前修改的bug是否为最新的bug分析
            return AjaxResult.error("当前的bug分析bug提交人已经测试确认，不允许再修改！！");
        }
        //查询bug（判断bug状态是否允许修改）
        Bugs bugs = bugsMapper.selectById(bugId);
        String bugStatus = bugs.getBugStatus();
        if(bugStatus.equals(BugsStatus.CLOSE.getStatus())||bugStatus.equals(BugsStatus.WAIVE.getStatus())){
            return AjaxResult.error("当前的bug状态下不允许再修改bug分析与对策！！");
        }
        baseMapper.updateById(analysis);

        //修改成功通知创建人
        //发送企业微信消息通知
        new Thread(()->{
            //根据用户id 查询用户
            SysUser sysUser = userMapper.selectUserById(bugs.getCreateUser());
            if(!ObjectUtils.isEmpty(sysUser)){
                String jobNumber = sysUser.getJobNumber();
                String msg="你好,"+sysUser.getUserName()+",你提报的bug编码为："+bugs.getBugCode()+"的bug，工程师修改了已回复的bug分析与对策";
                String msg1="请你尽快登录bugList系统进行查看最新的bug分析与对策，谢谢。系统登录链接为："+paramConfig.getLink();
                List<String> mesage=new ArrayList<>();
                mesage.add(msg);
                mesage.add(msg1);
                List<String> jN=new ArrayList<>();
                jN.add(jobNumber);
                weChatNoteUtils.sendWeChatNoteByJobNumber(jN,mesage);
            }
        }).start();
        return AjaxResult.success("修改成功");
    }

    @Override
    public AjaxResult findAnalysisLogByBid(Long bid) {
        if(ObjectUtils.isEmpty(bid)){
            return AjaxResult.error("查找的数据不能为空");
        }
        List<BugAnalysis> bugAnalyses = baseMapper.bugAnalysisLogByBid(bid);
        return AjaxResult.success(bugAnalyses);
    }
}
